package com.xp.kettlegenerate.start;

import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.trans.TransHopMeta;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.trans.steps.tableinput.TableInputMeta;
import org.pentaho.di.trans.steps.tableoutput.TableOutputMeta;

public class Test {

    public static void main(String[] args) {
        try {
            // 初始化 Kettle 环境
            KettleEnvironment.init();

            // 创建转换元数据对象
            TransMeta transMeta = new TransMeta();

            // 创建表输入步骤
            TableInputMeta tableInputMeta = new TableInputMeta();
            tableInputMeta.setDatabaseMeta(createDatabaseMeta()); // 设置数据库连接元数据
            tableInputMeta.setSQL("SELECT * FROM your_table");

            StepMeta tableInputStep = new StepMeta("Table Input", tableInputMeta);
            transMeta.addStep(tableInputStep);

            // 创建表输出步骤
            TableOutputMeta tableOutputMeta = new TableOutputMeta();
            tableOutputMeta.setDatabaseMeta(createDatabaseMeta()); // 设置数据库连接元数据
            tableOutputMeta.setTableName("output_table");

            StepMeta tableOutputStep = new StepMeta("Table Output", tableOutputMeta);
            transMeta.addStep(tableOutputStep);

            // 创建步骤之间的连接
            transMeta.addTransHop(new TransHopMeta(tableInputStep, tableOutputStep));

            // 保存转换为 KTR 文件
            String ktrFileName = "C:/Users/xp/Desktop/transformation.ktr";
            transMeta.setFilename(ktrFileName);
//            transMeta.saveToFile(ktrFileName);
            String xml = transMeta.getXML();
            Generate.saveMetaString(xml,ktrFileName);
            System.out.println("Transformation saved to: " + ktrFileName);
        } catch (KettleException e) {
            e.printStackTrace();
        }
    }

    // 创建数据库连接元数据
    private static DatabaseMeta createDatabaseMeta() {
        DatabaseMeta databaseMeta = new DatabaseMeta();
        databaseMeta.setName("SampleDB");
        databaseMeta.setDatabaseType("MySQL");
        databaseMeta.setDBName("your_database");
        databaseMeta.setHostname("localhost");
        databaseMeta.setDBPort("3306");
        databaseMeta.setUsername("your_username");
        databaseMeta.setPassword("your_password");
        return databaseMeta;
    }
}
